package net.lahuobao.finance.service.impl.accountrecord;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import net.lahuobao.finance.dao.AccountRecordMapper;
import net.lahuobao.finance.entity.account.AccountEntity;
import net.lahuobao.finance.entity.accountrecord.AccountRecord;
import net.lahuobao.finance.entity.accountrecord.EAccountRecordStatus;
import net.lahuobao.finance.entity.accountrecord.EAccountRecordType;
import net.lahuobao.finance.entity.criticallog.CriticalLog;
import net.lahuobao.finance.entity.criticallog.ECriticalType;
import net.lahuobao.finance.entity.paymentrecord.EPaymentRecordStatus;
import net.lahuobao.finance.entity.payupload.EPayUploadType;
import net.lahuobao.finance.entity.payupload.PayUploadEntity;
import net.lahuobao.finance.exception.AccountException;
import net.lahuobao.finance.service.accountrecord.AccountRecordServiceI;

import java.math.BigDecimal;
import java.util.Date;

import org.jeecgframework.core.common.service.impl.CommonServiceImpl;

@Service("accountRecordService")
@Transactional
public class AccountRecordServiceImpl extends CommonServiceImpl implements AccountRecordServiceI {
	@Autowired
	private AccountRecordMapper accountRecordDao;
	@Override
    @Transactional(value = "transactionManager", rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void audit(Integer accountRecordId, String comment, String operateId, String operateIp) {
        AccountRecord accountRecord = accountRecordDao.selectByPrimaryKey(accountRecordId);

        String remark = "审核通过：";
        remark = remark + comment;

        if (accountRecord != null) {
        	String update_status_sql=" update lahuobao.account_record set status ="+EAccountRecordStatus.ACCOUNT_RECORD_STATUS_WITHDRAW_AUDITED.getValue()+" where account_record_id =  "+accountRecordId;
        	this.updateBySqlString(update_status_sql);
        	String update_remark_sql="  update lahuobao.account_record set remark='"+remark+"' where account_record_id=  "+accountRecordId;
        	this.updateBySqlString(update_remark_sql);
        	String update_4withdrawAudit_sql=" update lahuobao.payment_record set status='"+EPaymentRecordStatus.PAYMENT_RECORD_STATUS_AUDITED.getValue()+"', operate_time=now(),  operate_id='"+operateId+"' where payment_record_id= "+accountRecord.getPayRecordId()+" and status=1 ";
        	this.updateBySqlString(update_4withdrawAudit_sql);
        }

        // log
        CriticalLog log = new CriticalLog();
        log.setOperateTime(new Date());
        log.setType(ECriticalType.ADMIN_SENSITIVE_INFO_TYPE_WITHDRAW_AUDIT.getValue());
        log.setRelatedId(accountRecordId);
        log.setOperateId(operateId);
        log.setOperateIp(operateIp);

        log.setComment(comment);
        save(log);
    }

    @Override
    @Transactional(value = "transactionManager", rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void reject(Integer accountRecordId, String comment, String operateId, String operateIp) {
        AccountRecord accountRecord = accountRecordDao.selectByPrimaryKey(accountRecordId);

        String remark = "驳回：";
        remark = remark + comment;

        AccountEntity account = this.findUniqueByProperty(AccountEntity.class, "accountId", accountRecord.getAccountId());
        account.setOperateTime(new Date());
        account.unFrozen(accountRecord.getAmount());
        this.getSession().merge(account);
        this.updateEntitie(account);

        String update_status_sql=" update lahuobao.account_record set status ="+EAccountRecordStatus.ACCOUNT_RECORD_STATUS_WITHDRAW_AUDIT_REJECT.getValue()+" where account_record_id =  "+accountRecordId;
    	this.updateBySqlString(update_status_sql);
    	String update_remark_sql="  update lahuobao.account_record set remark='"+remark+"' where account_record_id=  "+accountRecordId;
    	this.updateBySqlString(update_remark_sql);
        String update_4withdrawAudit_sql=" update lahuobao.payment_record set status='"+EPaymentRecordStatus.PAYMENT_RECORD_STATUS_WITHDRAW_AUDIT_REJECT.getValue()+"', operate_time=now(),  operate_id='"+operateId+"' where payment_record_id= "+accountRecord.getPayRecordId()+" and status=1 ";
    	this.updateBySqlString(update_4withdrawAudit_sql);
        // log
        CriticalLog log = new CriticalLog();
        log.setOperateTime(new Date());
        log.setType(ECriticalType.ADMIN_SENSITIVE_INFO_TYPE_WITHDRAW_AUDIT_REJECT.getValue());
        log.setRelatedId(accountRecordId);
        log.setOperateId(operateId);
        log.setOperateIp(operateIp);

        log.setComment(comment);
        save(log);
    }
    @Override
    @Transactional(value = "transactionManager", rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void pay(Integer accountRecordId, String path, String comment, String operateId, String
            operateIp, EAccountRecordType accountRecordType) throws Exception {
        AccountRecord accountRecord = accountRecordDao.selectByPrimaryKey(accountRecordId);
        
        AccountEntity account = this.findUniqueByProperty(AccountEntity.class, "accountId", accountRecord.getAccountId());
        BigDecimal total = (account.getUsable().add(account.getFrozen()));
        if (account == null || account.getTotal().compareTo(total) != 0) {
            throw new AccountException("账户金额异常！");
        } else {
            PayUploadEntity payUpload = new PayUploadEntity();
            payUpload.setAccountRecordId(accountRecordId);
            payUpload.setOperateType(EPayUploadType.PAY_UPLOAD_TYPE_WITHDRAW.getValue());
            payUpload.setPath(path);
            payUpload.setOperateId(operateId);
            payUpload.setOperateTime(new Date());
            save(payUpload);

            // log
            CriticalLog log = new CriticalLog();
            log.setOperateTime(new Date());
            log.setType(ECriticalType.ADMIN_SENSITIVE_INFO_TYPE_WITHDRAW_PAY.getValue());
            log.setRelatedId(accountRecordId);
            log.setOperateId(operateId);
            log.setOperateIp(operateIp);

            log.setComment(comment);
            save(log);

            // to do: 可用余额 =0 冻结账户 暂不实现
            if (account.getUsable().compareTo(new BigDecimal("0")) == 0) {

            }

            account.unFrozen4Withdraw(accountRecord.getAmount());
            
            String update_usableAndfrozenAndtotal_sql ="  update lahuobao.account set total = "+account.getTotal()+", usable ="+account.getUsable()+", frozen ="+account.getFrozen()+",  operate_Time = now()  where account_Id= "+account.getAccountId();
            this.updateBySqlString(update_usableAndfrozenAndtotal_sql);
            
            String update_4withdrawpay_sql=" update lahuobao.account_record set status="+EAccountRecordStatus.ACCOUNT_RECORD_STATUS_WITHDRAW_SUCCESS.getValue()+",  operate_type="+accountRecordType.getValue()+" where account_record_id= "+accountRecordId+" and status=10 ";
            this.updateBySqlString(update_4withdrawpay_sql);
            
            // accountRecordDao.updateRemark(accountRecordId,remark);

            // accountRecord.setOperateType(EAccountRecordType.ACCOUNT_RECORD_TYPE_WITHDRAW.getValue());//提现
            String update_paymentrecord_withdrawpay_sql="  update lahuobao.payment_record set status="+EPaymentRecordStatus.PAYMENT_RECORD_STATUS_WITHDRAW_SUCCESS.getValue()+","
            											+ "operate_time=now(), operate_id='"+operateId+"' where payment_record_id= "+accountRecord.getPayRecordId()+" and status=1";
            /*
            // to do: 发送短信给用户
            String sms_msg = "尊敬的客户,你已成功从拉货宝提现" + accountRecord.getAmount() + "元";
            organizationService.getOrganizationByOrganizationId(account.getOrganizationId());
            */
        }
    }

}